import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message, Loading } from 'element-ui'

const myaxios = axios.create({
  baseURL: 'http://127.0.0.1:3000'
})

let loading = null
let loadingRequestCount = 0 // 请求数量

// 显示 Loding
function showLoding (target) {
  if (loadingRequestCount === 0 && !loading) {
    loading = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)',
      target: target || 'body'
    })
  }
  loadingRequestCount += 1
}

// 隐藏 Loding
function hideLoding () {
  loadingRequestCount -= 1
  loadingRequestCount = Math.max(loadingRequestCount, 0)
  if (loadingRequestCount === 0) {
    loading.close()
    loading = null
  }
}

// 防抖
// const toHedeLoding = setTimeout(() => {
//   loading.close()
//   loading = null
// }, 300)

// 请求拦截器
myaxios.interceptors.request.use((config) => {
  showLoding()
  if (store.state.token) {
    config.headers.Authorization = store.state.token
  }
  return config
}, (error) => {
  hideLoding()
  Message.error('请求超时')
  return Promise.reject(error)
})

// 相应拦截器
myaxios.interceptors.response.use((response) => {
  hideLoding()
  return response
}, (error) => {
  if (error.response.status === 401) {
    store.commit('updateToken', '')
    store.commit('updateUserInfo', '')
    router.push('/push')
    Message.error('用户身份已过期,请重新登录!!!')
  }
  hideLoding()
  return Promise.reject(error)
})
export default myaxios
